package cn.yx.common.mdc.spring;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;

import java.util.Map;

/**
 * <p>Spring TaskDecorator装饰实现类，可支持MDC上下文信息</p>
 *
 * @author Wgssmart
 */
public class MdcTaskDecorator implements TaskDecorator {

    @Override
    @NonNull
    public Runnable decorate(@NonNull Runnable runnable) {
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        return () -> {
            if (!copyOfContextMap.isEmpty()) {
                MDC.setContextMap(copyOfContextMap);
            }
            try {
                runnable.run();
            } finally {
                if (!copyOfContextMap.isEmpty()) {
                    MDC.clear();
                }
            }
        };
    }
}
